package com.linkdood.app.service.impl;

import com.alibaba.fastjson.JSON;
import com.linkdood.app.dto.SignInfoDTO;
import com.linkdood.app.service.SyncMessageService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * @author cfj
 */
@Service
@Slf4j
public class SyncMessageServiceImpl implements SyncMessageService {
    /**
     * TODO 暂时写死，使用 123456 需要添加页面给用户展示该信息。
     */
    private static final String TOKEN = "123456";

    @Override
    public Object validateToken(String msg) {
        // 返回结果默认 false
        Map<String, Object> result = new HashMap<>(1);
        result.put("msg", false);
        try {
            SignInfoDTO signInfo = JSON.parseObject(msg, SignInfoDTO.class);
            if (signInfo == null) {
                return result;
            }
            List<String> list = new ArrayList<>();
            list.add(TOKEN);
            list.add(signInfo.getEntId());
            list.add(signInfo.getTimestamp());
            list.add(signInfo.getNonce());
            result.put("msg", validateSign(list, signInfo.getSignature()));
        } catch (Exception e) {
            log.error("validateToken error : {}", e.getMessage());
        }
        return result;
    }

    /**
     * 校验签名
     *
     * @param list      生成签名列表信息
     * @param signature 签名
     * @return true 通过校验
     */
    private boolean validateSign(List<String> list, String signature) {
        // 字典排序
        Collections.sort(list);
        String st = StringUtils.arrayToDelimitedString(list.toArray(), "");

        // sha1
        String sign = DigestUtils.sha1Hex(st);
        return sign.equals(signature);
    }
}
